# -*- coding:utf8 -*-
import pyssdb
import typing
import json
import traceback
from scrapy import FormRequest
from squirrel_core.commons.utils.get_config import get_config
from squirrel_core.frame.spider_makaka import MakakaSpider
from squirrel_spiders.shuzixindong.password_encrypt import *


class shuzixindong_login(MakakaSpider):
    name = "shuzixindong_login"
    login_url = "https://api-changzheng.chinaath.com/changzheng-user-center-api/login"
    header = {
        "machineCode": "6bd839d8b9f7f76d",
        "osId": "1002",
        "device": "pad/12 HUAWEI MGA-AL00",
        "versionNumber": "519",
        "versionCode": "5.54.0",
        "terminalType": "1",
        "Content-Type": "application/x-www-form-urlencoded",
        "Host": "api-changzheng.chinaath.com",
    }
    serialNumber = ""
    base_config = get_config(sections="base")
    ssdb_host = base_config.get('ssdb_host')
    ssdb_port = base_config.get('ssdb_port')

    def get_ext_requests_or_urls(self, data=None):
        try:
            if data and isinstance(data, str):
                data = json.loads(data)
            if data and isinstance(data, typing.MutableMapping):
                self.serialNumber = data.get("serialNumber", "")
                self.logger.info("开始登录")
                phone = data.get("phone", "13981808836")
                pwd = data.get("password", "aa123456")
                password = encrypt_password(pwd)
                login_data = {"loginType": "0", "password": password, "phone": phone, "encryptType": "1"}
                yield FormRequest(url=self.login_url, formdata=login_data, callback=self.parse,
                                  headers=self.header, dont_filter=True, errback=self.err_parse)
        except Exception:
            self.logger.error(f"登录时出错：{traceback.format_exc()}")

    def parse(self, response, **kwargs):
        try:
            self.logger.info("开始保存cookie")
            data = json.loads(response.text)
            token = data.get("data", {}).get("token", "")
            c = pyssdb.Client(host=self.ssdb_host, port=self.ssdb_port)
            c.qclear("shuzixindong_cookie")
            c.qpush_front("shuzixindong_cookie", token)
            c.disconnect()
        except Exception:
            self.logger.info(f"保存cookie时出错：{traceback.format_exc()}")

    def err_parse(self, failure):
        self.logger.warning(f"请求失败：{failure.request.url},错误原因:{traceback.format_exc()}")
